<?php
declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */

namespace App\Controller\Admin;

use App\Controller\AppBaseController;
use App\Model\Act;
use App\Model\ActAnswerAnswer;
use App\Model\ActAnswerJoin;
use App\Model\ActAnswerLog;
use App\Model\ActAnswerQuestion;
use App\Model\ActAnswerRule;
use App\Model\ActJoin;

use App\Model\ActPrizeGoods;
use App\Model\ActPrizeJoin;
use App\Model\ActPrizeRule;
use App\Model\ActPush;
use App\Model\ActSurveyAnswer;
use App\Model\ActSurveyLog;
use App\Model\ActSurveyQuestion;
use App\Model\ActSurveyRule;
use App\Model\ActVoteRule;
use App\Model\Notify;
use App\Model\Party;
use App\Model\User;
use App\Service\NotifyQueueService;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\Di\Annotation\Inject;
use App\Middleware\AdminApiAuth;


use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

#[Controller(prefix: 'admin')]
#[Middleware(AdminApiAuth::class)]
class ActController extends AppBaseController
{
    #[Inject] protected NotifyQueueService $notifyQueueService;

    /**
     * 后台--活动中心活动列表
     * @param int $type  -1:全部 1：答题 2：报名 3：抽奖 4：打卡 5：问卷 5：投票
     * @return object
     */
    #[RequestMapping(path:'actList/{type}',methods: 'get')]
    public function actList(int $type=-1): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where = [];
            if($type!=-1){
                $where['type'] = $type;
            }
            //指定支部
            if($_admin->level==1){
                $party_id = $this->request->input('party_id', null);
                if($party_id){
                    $where['party_id'] = $party_id;
                }
            }else{
                $where['party_id'] = $_admin->party_id;
            }
            $list = Act::where($where)
                ->selectRaw('id,party_id,title,start_time,end_time,status,created_at')
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();

            $total = 0;
            $next = 0;
            if($list->isNotEmpty()){
                if($page==1) $total = Act::where($where)->count();
                if(count($list)>$limit) $next = 1;
                foreach ($list as $key=>$value){
                    if(time()<=strtotime($value->start_time)){
                        $value->status = 0;
                    }
                    if(time()>strtotime($value->end_time)){
                        $value->status = 2;
                    }
                }
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next,'total'=>$total]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--活动中心活动详情
     * @param int $act_id
     * @return object
     */
    #[RequestMapping(path:'actInfo/{act_id}',methods: 'get')]
    public function actInfo(int $act_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $intInfo = Act::where('id',$act_id)->first();
            if(empty($intInfo)) return $this->reMsg->re(10008);
            if($intInfo->type==1){
                //答题
                $info = Act::with(['answerRule'=>function($query){
                    $query->first();
                }])->where('id',$act_id)->first();
            }else if($intInfo->type==3){
                //抽奖
                $info = Act::with(['prizeRule'=>function($query){
                    $query->first();
                }])->where('id',$act_id)->first();
            }else if($intInfo->type==5){
                //问卷
                $info = Act::with(['surveyRule'=>function($query){
                    $query->first();
                }])->where('id',$act_id)->first();
            }else if($intInfo->type==6){
                //投票
                $info = Act::with(['voteRule'=>function($query){
                    $query->first();
                }])->where('id',$act_id)->first();
            }else{
                //其他【报名、打卡】
                $info = Act::where('id',$act_id)->first();
            }
            return $this->reMsg->re(1,'success',$info);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--支活动中心活动发布|编辑
     * @param int|null $act_id
     * @return object
     */
    #[RequestMapping(path: 'actEdit[/{act_id}]',methods: 'post,get')]
    public function actEdit(int|null $act_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $data = $this->request->all();

            //虚拟数据
//            if(empty($data)){
//                $data['type'] = 2; //[1,2,3,4,5]  1：答题 2：报名 3：抽奖 4：打卡 5：问卷
//                $data['title'] = '报名打卡';
//                $data['photo'] = 'fqxinyi23/test/xyWords/xyWords1691110928830.jpg';
//                $data['content'] = '答题答题答题答题答题答题答题答题答题答题答题答题';
//                $data['start_time'] = '2024-06-14 12:00:00';
//                $data['end_time'] = '2024-06-30 12:00:00';
//                $data['max_limit'] = 1; //限制总人数
//                $data['collect_info'] = ['手机号','年龄','性别']; //收集报名信息 用|隔开


                //答题参数
//                $data['type'] = 1;
//                $data['title'] = '答题';
//                $data['extract_type'] = 1; //抽题方式  1：顺序抽取 2：随机抽取 3：指定类型抽取
//                $data['extract_num'] = 10; //抽题数量
//                $data['dan_num'] = 2; //抽题单选数量
//                $data['duo_num'] = 3; //抽题多选数量
//                $data['pan_num'] = 3; //抽题判断数量
//                $data['rule'] = '规则2';
//                $data['limit_type'] = 1; //限制类型 1：总共 2：每天
//                $data['limit_time'] = 1; //次数限制
//                $data['rank'] = 0; //是否排行 0：否 1：是

                //答题参数
//                $data['type'] = 3;
//                $data['title'] = '抽奖';
//                $data['rule'] = '规则3';
//                $data['percent'] = 20; //百分比 10-100 十的倍数
//                $data['limit_type'] = 1; //限制类型 1：总共 2：每天
//                $data['limit_time'] = 1; //次数限制
//                $data['rank'] = 0; //是否排行 0：否 1：是

                //问卷参数
//                $data['type'] = 5;
//                $data['title'] = '问卷';
//                $data['rule'] = '规则3';
//                $data['limit_type'] = 1; //限制类型 1：总共 2：每天
//                $data['limit_time'] = 1; //次数限制
//                $data['rank'] = 0; //是否排行 0：否 1：是
//            }
            //虚拟数据

            if(empty($data['type'])
                || empty($data['title'])
                || empty($data['photo'])
                || empty($data['start_time'])
                || empty($data['end_time'])
            ) return $this->reMsg->re(10007);

            //判断明细
            if(!in_array($data['type'],[1,2,3,4,5,6])) return $this->reMsg->re(0,'活动类型不存在');
            if(strtotime($data['start_time'])<=time())  return $this->reMsg->re(0,'开始时间应晚于现在时间');
            if(strtotime($data['end_time'])<=strtotime($data['start_time']))  return $this->reMsg->re(0,'结束时间应晚于开始时间');

            //报名和打卡限制活动
            if(empty($data['max_limit']) || !is_numeric($data['max_limit']) || $data['max_limit']<=0) $data['max_limit'] = null;

            //指定支部（无需指定）
            if($_admin->level==1){
//                if(empty($data['party_id'])) return $this->reMsg->re(10007);
//                $party_id = $data['party_id'];
                $party_id = $_admin->party_id;
            }else{
                $party_id = $_admin->party_id;
            }

            //答题
            if($data['type']==1){
                if(!isset($data['extract_type']) || !in_array($data['extract_type'],[1,2]) ||
                    !isset($data['rule']) || $data['rule']==null
                ) return $this->reMsg->re(10007);
                //字段验证
                if(empty($data['extract_num']) || !is_numeric($data['extract_num'])) $data['extract_num'] = 0;
                if(empty($data['dan_num']) || !is_numeric($data['dan_num'])) $data['dan_num'] = 0;
                if(empty($data['duo_num']) || !is_numeric($data['duo_num'])) $data['duo_num'] = 0;
                if(empty($data['pan_num']) || !is_numeric($data['pan_num'])) $data['pan_num'] = 0;
                if(empty($data['limit_type']) || !is_numeric($data['limit_type'])) $data['limit_type'] = 1;
                if(empty($data['limit_time']) || !is_numeric($data['limit_time'])) $data['limit_time'] = 1;
                if(empty($data['is_rank']) || !is_numeric($data['is_rank'])) $data['is_rank'] = 0;
            }

            //报名
            if($data['type']==2){
                if(!isset($data['collect_option']) || !is_array($data['collect_option'])) $data['collect_option'] = [];
            }

            //抽奖
            if($data['type']==3){
                $percentArray = [10,20,30,40,50,60,70,80,90,100];
                if(!isset($data['percent']) || !in_array($data['percent'],$percentArray) ||
                    !isset($data['rule']) || $data['rule']==null
                ) return $this->reMsg->re(10007);
                //字段验证
                if(empty($data['percent']) || !is_numeric($data['percent'])) $data['percent'] = 10;
                if(empty($data['template']) || !is_numeric($data['template'])) $data['template'] = 1;
                if(empty($data['limit_type']) || !is_numeric($data['limit_type'])) $data['limit_type'] = 1;
                if(empty($data['limit_time']) || !is_numeric($data['limit_time'])) $data['limit_time'] = 1;
                if(empty($data['is_rank']) || !is_numeric($data['is_rank'])) $data['is_rank'] = 0;
            }

            //打卡
            if($data['type']==4){
                if(empty($data['banner'])) return $this->reMsg->re(10007,'打卡banner图不可为空');
            }

            //问卷
            if($data['type']==5){
                if(!isset($data['rule']) || $data['rule']==null) return $this->reMsg->re(10007);
                //字段验证
                if(empty($data['limit_type']) || !is_numeric($data['limit_type'])) $data['limit_type'] = 1;
                if(empty($data['limit_time']) || !is_numeric($data['limit_time'])) $data['limit_time'] = 1;
                if(empty($data['is_rank']) || !is_numeric($data['is_rank'])) $data['is_rank'] = 0;
            }

            //投票 ~涉及推送
            $userArr = [];
            if($data['type']==6){
                if(!isset($data['rule']) || $data['rule']==null) return $this->reMsg->re(10007);
                //字段验证
                if(empty($data['limit_num']) || !is_numeric($data['limit_num'])) $data['limit_num'] = 1;


                //验证推送数据
                if(!isset($data['push_all']) || !in_array($data['push_all'],[0,1])) return $this->reMsg->re(10007,'推送标签未选择1');
                if(!isset($data['push_user']) || !is_array($data['push_user'])) return $this->reMsg->re(10007,'推送标签未选择2');
                if(!isset($data['push_tip']) || !is_array($data['push_tip'])) return $this->reMsg->re(10007,'推送标签未选择3');
                if(!isset($data['push_party']) || !is_array($data['push_party'])) return $this->reMsg->re(10007,'推送标签未选择4');

                //推送全员
                $temp_arr = [];
                if($data['push_all']==1){
                    $userArr = User::where('status',1)->whereNotNull('auth_time')->pluck('id')->toArray();
                }else{
                    //指定推送
                    if($data['push_user']){
                        $userList = User::where('status',1)->whereNotNull('auth_time')->whereIn('id',$data['push_user'])->pluck('id')->toArray();
                        $temp_arr = array_merge($temp_arr,$userList);
                    }
                    if($data['push_party']){
                        $partyUserList = User::where('status',1)->whereNotNull('auth_time')->whereIn('party_id',$data['push_party'])->pluck('id')->toArray();
                        $temp_arr = array_merge($temp_arr,$partyUserList);
                    }
                    if($data['push_tip']) {
                        $tipUserList = User::where('status', 1)->whereNotNull('auth_time')->whereIn('user_type', $data['push_tip'])->pluck('id')->toArray();
                        $temp_arr = array_merge($temp_arr,$tipUserList);
                    }
//                    if(empty($userArr)) return $this->reMsg->re(0,'推送标签未选择');
                    $userArr = array_values(array_unique($temp_arr));
                }
            }

            if(empty($data['content'])) $data['content'] = null;
//            empty($data['status']) || !is_numeric($data['status']) ? $data['status'] = 0 : $data['status'] = 1;


            Db::beginTransaction();

            if($act_id){
                //编辑
                $info = Act::where('id',$act_id)->first();
                if(empty($info)){
                    Db::rollBack();
                    return $this->reMsg->re(10008);
                }

                //验证权限 （超级管理员或者创建者）
                if($_admin->level!=1 && $_admin->admin_id!=$info->admin_id){
                    Db::rollBack();
                    return $this->reMsg->re(10009);
                }

                $info->type = $data['type'];
                $info->title = $data['title'];
                $info->content = $data['content'];
                $info->photo = $data['photo'];
                $info->start_time = $data['start_time'];
                $info->end_time = $data['end_time'];
                $info->max_limit = $data['max_limit'];
                if($data['type']==2){
                    $info->collect_option = $data['collect_option'];
                }
                $info->party_id = $party_id;
                $info->admin_id = $_admin->id;
                $info->save();
                //查询更新答题数据
                if($data['type']==1){
                    $answerRuleInfo = ActAnswerRule::where('act_id',$act_id)->first();
                    if($answerRuleInfo){
                        $answerRuleInfo->extract_type = $data['extract_type'];
                        $answerRuleInfo->extract_num = $data['extract_num'];
                        $answerRuleInfo->dan_num = $data['dan_num'];
                        $answerRuleInfo->duo_num = $data['duo_num'];
                        $answerRuleInfo->pan_num = $data['pan_num'];
                        $answerRuleInfo->rule = $data['rule'];
                        $answerRuleInfo->limit_type = $data['limit_type'];
                        $answerRuleInfo->limit_time = $data['limit_time'];
                        $answerRuleInfo->is_rank = $data['is_rank'];
                        $answerRuleInfo->save();
                    }else{
                        //添加答题规则
                        $extraData['act_id'] = $act_id;
                        $extraData['extract_type'] = $data['extract_type'];
                        $extraData['extract_num'] = $data['extract_num'];
                        $extraData['dan_num'] = $data['dan_num'];
                        $extraData['duo_num'] = $data['duo_num'];
                        $extraData['pan_num'] = $data['pan_num'];
                        $extraData['rule'] = $data['rule'];
                        $extraData['limit_type'] = $data['limit_type'];
                        $extraData['limit_time'] = $data['limit_time'];
                        $extraData['is_rank'] = $data['is_rank'];
                        ActAnswerRule::create($extraData);
                    }
                }

                //查询更新抽奖规则数据
                if($data['type']==3){
                    $prizeRuleInfo = ActPrizeRule::where('act_id',$act_id)->first();
                    if($prizeRuleInfo){
                        $prizeRuleInfo->percent = $data['percent'];
                        $prizeRuleInfo->template = $data['template'];
                        $prizeRuleInfo->rule = $data['rule'];
                        $prizeRuleInfo->limit_type = $data['limit_type'];
                        $prizeRuleInfo->limit_time = $data['limit_time'];
                        $prizeRuleInfo->is_rank = $data['is_rank'];
                        $prizeRuleInfo->save();
                    }else{
                        //添加答题规则
                        $extraData['act_id'] = $act_id;
                        $extraData['percent'] = $data['percent'];
                        $extraData['template'] = $data['template'];
                        $extraData['rule'] = $data['rule'];
                        $extraData['limit_type'] = $data['limit_type'];
                        $extraData['limit_time'] = $data['limit_time'];
                        $extraData['is_rank'] = $data['is_rank'];
                        ActPrizeRule::create($extraData);
                    }
                }

                //查询更新问卷规则数据
                if($data['type']==5){
                    $surveyRuleInfo = ActSurveyRule::where('act_id',$act_id)->first();
                    if($surveyRuleInfo){
                        $surveyRuleInfo->rule = $data['rule'];
                        $surveyRuleInfo->limit_type = $data['limit_type'];
                        $surveyRuleInfo->limit_time = $data['limit_time'];
                        $surveyRuleInfo->is_rank = $data['is_rank'];
                        $surveyRuleInfo->save();
                    }else{
                        //添加问卷规则
                        $extraData['act_id'] = $act_id;
                        $extraData['rule'] = $data['rule'];
                        $extraData['limit_type'] = $data['limit_type'];
                        $extraData['limit_time'] = $data['limit_time'];
                        $extraData['is_rank'] = $data['is_rank'];
                        ActSurveyRule::create($extraData);
                    }
                }
                Db::commit();
                return $this->reMsg->re(1);
            }else{
                $data['party_id'] = $party_id;
                $data['admin_id'] = $_admin->id;
                $insertRet = Act::create($data);
                if($insertRet){
                    $extraData['act_id'] = $insertRet->id;
                    //这里面需要添加对应活动的附加规则
                    //添加答题规则
                    if($data['type']==1){
                        $extraData['extract_type'] = $data['extract_type'];
                        $extraData['extract_num'] = $data['extract_num'];
                        $extraData['dan_num'] = $data['dan_num'];
                        $extraData['duo_num'] = $data['duo_num'];
                        $extraData['pan_num'] = $data['pan_num'];
                        $extraData['rule'] = $data['rule'];
                        $extraData['limit_type'] = $data['limit_type'];
                        $extraData['limit_time'] = $data['limit_time'];
                        $extraData['is_rank'] = $data['is_rank'];
                        ActAnswerRule::create($extraData);
                    }

                    //添加抽奖规则
                    if($data['type']==3){
                        $extraData['percent'] = $data['percent'];
                        $extraData['template'] = $data['template'];
                        $extraData['rule'] = $data['rule'];
                        $extraData['limit_type'] = $data['limit_type'];
                        $extraData['limit_time'] = $data['limit_time'];
                        $extraData['is_rank'] = $data['is_rank'];
                        ActPrizeRule::create($extraData);
                    }

                    //添加问卷规则
                    if($data['type']==5){
                        $extraData['rule'] = $data['rule'];
                        $extraData['limit_type'] = $data['limit_type'];
                        $extraData['limit_time'] = $data['limit_time'];
                        $extraData['is_rank'] = $data['is_rank'];
                        ActSurveyRule::create($extraData);
                    }

                    //添加投票规则
                    if($data['type']==6){
                        $extraData['rule'] = $data['rule'];
                        $extraData['limit_num'] = $data['limit_num'];
                        $extraData['push_all'] = $data['push_all'];
                        $extraData['push_user'] = $data['push_user'];
                        $extraData['push_party'] = $data['push_party'];
                        $extraData['push_tip'] = $data['push_tip'];
                        ActVoteRule::create($extraData);
                        //执行推送
                        if($userArr){
                            $i=0;
                            foreach ($userArr as $user){
                                $pushInsertData[$i]['party_id'] = $insertRet->party_id;
                                $pushInsertData[$i]['act_id'] = $insertRet->id;
                                $pushInsertData[$i]['act_type'] = 6;
                                $pushInsertData[$i]['uid'] = $user;
                                $pushInsertData[$i]['push_time'] = date('Y-m-d H:i:s');
                                $i++;
                            }
                        }
                        Db::table('act_push')->insert($pushInsertData);
                    }

                    //执行消息队列任务
                    //不发布就推送 ，点击上线时候推送
                    //$this->notifyQueueService->pushAct(['id'=>$insertRet->id],5);
                    Db::commit();
                    return $this->reMsg->re(1);
                }else{
                    Db::rollBack();
                    return $this->reMsg->re(0);
                }
            }
        }catch (\Exception $exception){
            Db::rollBack();
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--活动中心活动|删除
     * @param int $act_id
     * @return object
     */
    #[RequestMapping(path:'actDelete/{act_id}',methods: 'get')]
    public function actDelete(int $act_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            //判断信息
            $info = Act::where('id',$act_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            //验证权限 （超级管理员或者创建者）
            if($_admin->level!=1 && $_admin->admin_id!=$info->admin_id) return $this->reMsg->re(10009);

            Db::beginTransaction();

            //查询该活动是否由记录
            $whereDelete['act_id'] = $act_id;
            if($info->type==1){
                //答题
                ActAnswerQuestion::where($whereDelete)->delete();
                ActAnswerAnswer::where($whereDelete)->delete();
                ActAnswerRule::where($whereDelete)->delete();
                ActAnswerJoin::where($whereDelete)->delete();
                ActAnswerLog::where($whereDelete)->delete();
            }else if($info->type==3){
                //抽奖
                ActPrizeGoods::where($whereDelete)->delete();
                ActPrizeRule::where($whereDelete)->delete();
                ActPrizeJoin::where($whereDelete)->delete();
            }else if($info->type==5){
                //问卷
                ActSurveyQuestion::where($whereDelete)->delete();
                ActSurveyAnswer::where($whereDelete)->delete();
                ActSurveyRule::where($whereDelete)->delete();
                ActSurveyLog::where($whereDelete)->delete();
            }
            //删除参与主体记录
            ActJoin::where($whereDelete)->delete();

            //删除活动主体
            $info->delete();

            //同时删除自己的关联通知
            $notifyWhere['module'] = 3; //在线活动
            $notifyWhere['relation_id'] = $act_id;
            Notify::where($notifyWhere)->delete();

            Db::commit();
            return $this->reMsg->re(1);
        }catch (\Exception $exception){
            Db::rollBack();
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     * 后台--活动活动参与人
     * @param int $act_id
     * @return object
     */
    #[RequestMapping(path: 'actJoinList/{act_id}',methods: 'get')]
    public function actJoinList(int $act_id) :object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            //先获取本次答题活动
            $info = Act::where('id',$act_id)->selectRaw('id,type')->first();
            if(empty($info)) return $this->reMsg->re(10008);
            if(!in_array($info->type,[2,4])) return $this->reMsg->re(0,'活动类型有误');

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where['act_id'] = $act_id;
            $list = ActJoin::with(['user'=>function($query){
                    $query->selectRaw('id,nickname,avatar,auth_name')->first();
                }])
                ->where($where)
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();

            $total = 0;
            $next = 0;
            if($list->isNotEmpty()){
                if($page==1) $total = ActJoin::where($where)->count();
                if(count($list)>$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next,'total' => $total]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }




    /**
     * 后台--活动中心活动|上线下线
     * @param int $act_id
     * @return object
     */
    #[RequestMapping(path:'actStatusChange/{act_id}',methods: 'get')]
    public function actStatusChange(int $act_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            //判断信息
            $info = Act::where('id',$act_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            //验证权限 （超级管理员或者创建者）
            if($_admin->level!=1 && $_admin->admin_id!=$info->admin_id) return $this->reMsg->re(10009);
            if($info->status==1){
                $info->status=0;
            }else{
                $info->status=1;
                //查询是否已经推送
                $pushWhere['module'] = 3; //在线活动
                $pushWhere['relation_id'] = $info->id;
                $notifyInfo = Notify::where($pushWhere)->first();
                if(empty($notifyInfo)){
                    //执行消息队列任务
                    //不发布就推送 ，点击上线时候推送
                    $this->notifyQueueService->pushAct(['id'=>$info->id],5);
                }
            }
            $info->save();
            return $this->reMsg->re(1);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }




    /**
     * 后台--活动中心活动|结果导出
     * @param int $act_id
     * @return object
     */
    #[RequestMapping(path:'actResultExport/{act_id}',methods: 'get')]
    public function actResultExport(int $act_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            //判断信息
            $info = Act::where('id',$act_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);

            if(!in_array($info->type,[1,2,3,4,5])) return $this->reMsg->re(0,'活动类型有误');

            // 表头
            $headers = [];
            // 模拟数据
            $data = [];

            if($info->type==1){
                //导出答题排行榜
                $headers = ['编号ID','姓名','工号','部门','总分','时间'];

                $joinList = ActAnswerJoin::with(['user'=>function($query){
                        $query->selectRaw('id,auth_name,auth_key,department')->get();
                    }])
                    ->where('act_id',$act_id)
                    ->selectRaw('id,uid,answer_total_score,created_at')
                    ->orderByDesc('answer_total_score')
                    ->orderBy('created_at')
                    ->get();
                if($joinList->isNotEmpty()){
                    $joinList = $joinList->toArray();
                    foreach ($joinList as $key=>$value){
                        $data[$key][0] = $value['id'];
                        $data[$key][1] = null;
                        $data[$key][2] = null;
                        $data[$key][3] = null;
                        $data[$key][4] = null;
                        if($value['user']!=null){
                            $data[$key][1] = $value['user']['auth_name'];
                            $data[$key][2] = $value['user']['auth_key'];
                            $data[$key][3] = $value['user']['department'];
                            $data[$key][4] = $value['answer_total_score'];
                        }
                        $data[$key][5] = $value['created_at'];
                    }
                }
            }

            //导出报名或打卡记录
            if($info->type==2 || $info->type==4){
                $headers = ['编号ID', '姓名', '工号','部门','时间'];
                $joinList = ActJoin::with(['user'=>function($query){
                        $query->selectRaw('id,auth_name,auth_key,department')->get();
                    }])
                    ->selectRaw('id,uid,created_at')
                    ->where('act_id',$info->id)
                    ->get();
                if($joinList->isNotEmpty()){
                    $joinList = $joinList->toArray();
                    foreach ($joinList as $key=>$value){
                        $data[$key][0] = $value['id'];
                        $data[$key][1] = null;
                        $data[$key][2] = null;
                        $data[$key][3] = null;
                        if($value['user']!=null){
                            $data[$key][1] = $value['user']['auth_name'];
                            $data[$key][2] = $value['user']['auth_key'];
                            $data[$key][3] = $value['user']['department'];
                        }
                        $data[$key][4] = $value['created_at'];
                    }
                }
            }

            //导出中奖记录
            if ($info->type==3){
                //导出答题排行榜
                $headers = ['编号ID','姓名','工号','部门','是否中奖','中奖奖品','时间'];

                $joinList = ActPrizeJoin::with(['user'=>function($query){
                        $query->selectRaw('id,auth_name,auth_key,department')->get();
                    }])
                    ->where('act_id',$act_id)
                    ->selectRaw('id,uid,status,prize_goods_name,created_at')
                    ->orderBy('created_at')
                    ->get();
                if($joinList->isNotEmpty()){
                    $joinList = $joinList->toArray();
                    foreach ($joinList as $key=>$value){
                        $data[$key][0] = $value['id'];
                        $data[$key][1] = null;
                        $data[$key][2] = null;
                        $data[$key][3] = null;
                        if($value['user']!=null){
                            $data[$key][1] = $value['user']['auth_name'];
                            $data[$key][2] = $value['user']['auth_key'];
                            $data[$key][3] = $value['user']['department'];
                        }
                        $data[$key][4] = '未中奖';
                        if($value['status']==1){
                            $data[$key][4] = '已中奖';
                        }
                        $data[$key][5] = $value['prize_goods_name'];
                        $data[$key][6] = $value['created_at'];
                    }
                }
            }

            //问卷记录导出
            if ($info->type==5){
                //导出问卷
                $headers = ['编号ID','姓名','工号','部门','时间'];
                $data = [];

                //获取该活动的参与用户信息
                $surveyJoinList = ActJoin::with(['user'=>function($query){
                                        $query->selectRaw('id,auth_name,auth_key,department')->get();
                    }])->where('act_id',$act_id)
                    ->selectRaw('id,act_id,uid,title,created_at')
                    ->get();

                //获取活动-调研问题
                $titleIndex = 4;
                $surveyQuestionList = ActSurveyQuestion::where('act_id',$act_id)->selectRaw('id,type,question_title')->get();
                $surveyQuestionStatus = false;
                if($surveyQuestionList->isNotEmpty()){
                    $surveyQuestionStatus = true;
                    $surveyQuestionList = $surveyQuestionList->toArray();
                    foreach ($surveyQuestionList as $qKey=>$qVal){
                        $headers[$titleIndex++] = $qVal['question_title'];
                    }
                }

                if($surveyJoinList->isNotEmpty()){
                    $surveyJoinList = $surveyJoinList->toArray();
                    //获取活动-调研用户提交数据
                    $surveyLogList = ActSurveyLog::where('act_id',$act_id)->get();
                    $surveyLogStatus = false;
                    if($surveyLogList->isNotEmpty()){
                        $surveyLogStatus = true;
                        $surveyLogList = $surveyLogList->toArray();
                    }
                    foreach ($surveyJoinList as $jKey=>$jVal){
                        $data[$jKey][0] = $jVal['id'];
                        $data[$jKey][1] = null;
                        $data[$jKey][2] = null;
                        $data[$jKey][3] = null;
                        if($jVal['user']!=null){
                            $data[$jKey][1] = $jVal['user']['auth_name'];
                            $data[$jKey][2] = $jVal['user']['auth_key'];
                            $data[$jKey][3] = $jVal['user']['auth_key'];
                        }
                        $data[$jKey][4] = $jVal['created_at'];

                        //整理用户记录
                        if($surveyQuestionStatus && $surveyLogStatus){
                            $textIndex = 4;
                            foreach ($surveyQuestionList as $qqKey=>$qqVal){
                                foreach ($surveyLogList as $lKey=>$lVal){
                                    if($qqVal['id']==$lVal['question_id'] && $jVal['uid']==$lVal['uid']){
                                        $data[$jKey][$textIndex] = $lVal['question_answer'];
                                    }
                                }
                                $textIndex++;
                            }
                        }
                    }
                }
            }

            // 文件名
            $fileName = 'act-'.$info->id.'-'.time();
            $newFilename =  $fileName.'.xlsx';// 这是原本要导出的文件名

            //环境信息
            $upload_path = $this->upload_path;
            $app_name = config('app_name');
            $app_env = config('app_env');

            //文件详细目录
            $fileDescPath = '/export/'.date('Ymd',time());

            //保存路径
            $savePath = $upload_path;
            if($app_env) $savePath .= '/'.$app_env;
            $savePath .= $fileDescPath;
            //保存路径不存在就创建
            if(!file_exists($savePath)){
                self::createDir($savePath);
            }
            $savePath .= '/'.$newFilename;

            //访问路径
            $webPath = '';
            if($app_env) $webPath .= '/'.$app_name;
            if($app_env) $webPath .= '/'.$app_env;
            $webPath .= $fileDescPath.'/'.$newFilename;

//            var_dump($data);
//            return $this->reMsg->re(0);

            // 调用导出方法
            self::export($headers,$data,$savePath,$fileName);
            return $this->reMsg->re(1,'success',['file_url'=>$webPath]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 导出
     * @param $headers
     * @param $data
     * @param $filePath
     * @param $title
     * @return void
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    static function export($headers,$data,$filePath,$title = null):void
    {
        // 创建Excel对象
        $spreadsheet = new Spreadsheet();

        // 设置工作表名称
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->setTitle($title ?: 'Sheet1');

        // 写入表头
        foreach ($headers as $key => $header) {
            $column = chr(65 + intval($key)); // 列名，如A、B、C...
            $worksheet->setCellValue($column.'1', $header);
        }

        // 写入数据
        $row = 2; // 数据行起始行号
        foreach ($data as $item) {
            foreach ($item as $key => $value) {
                $column = chr(65 + intval($key)); // 列名，如A、B、C...
                $worksheet->setCellValue($column.$row, $value);
            }
            $row++;
        }
        // 导出Excel文件
        $writer = new Xlsx($spreadsheet);
        $writer->save($filePath);
    }


    /**
     * 功能：循环检测并创建文件夹
     * @param $path
     * @return null
     */
    static function createDir($path){
        if (!file_exists($path)){
            static::createDir(dirname($path));
            mkdir($path, 0777); //检查是否有该文件夹，如果没有就创建，并给予最高权限
        }
    }




}